package com.cxria.problem.exception

import com.cxria.problem.dto.Status
import com.cxria.problem.enums.StatusCodeEnum
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody

@ControllerAdvice
class DefaultExceptionHandler {

	final Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class)

	@Autowired
    ObjectMapper objectMapper

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
    Status exception(Exception ex) {
		Status status
		String message = ex.getMessage()
		String msg = ex.getClass().getName() + ' : ' + message
		try {
			status = objectMapper.readValue(message, Status.class)
			logger.error(objectMapper.writeValueAsString(status))
		} catch (e) {
			status = new Status(Status.ERROR, StatusCodeEnum.UNKNOWN_ERROR, msg)
			logger.error(objectMapper.writeValueAsString(status))
			ex.printStackTrace()
		}
		status
	}

}
